package com.test.thread;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class ThreadSyncLockMain {
    private static volatile List<String> list = new ArrayList<>();

    public void add() {
        list.add("wuk");
    }

    public  int size() {

        return list.size();
    }

    public static void main(String[] args) throws InterruptedException {
        ThreadSyncLockMain list1 = new ThreadSyncLockMain();
        Object obj = new Object();
        Thread t1 = new Thread(new Runnable() {

            @Override
            public void run() {
                synchronized (obj) {
                    System.out.println("t1线程启动。。。。");
                    for (int i = 0; i < 10; i++) {
                        list1.add();
                        System.out.println("当前线程" + Thread.currentThread().getName() + "添加了一个元素");
                        try {
                            Thread.sleep(1000);
                            if (list1.size() == 5) {
                                System.out.println("已经发出通知。。");
                                obj.notify();
                            }
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                }
            }
        },"t1");

        Thread t2 = new Thread (new Runnable() {

            @Override
            public void run() {
                synchronized (obj) {
                    System.out.println("t2启动。。。");
                    if (list1.size() != 5) {
                        try {
                            System.out.println("t2启动。。。 wait start");
                            obj.wait();
                            System.out.println("t2启动。。。 wait finish");
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                    System.out.println("当前线程：" + Thread.currentThread().getName() + "收到通知线程停止..");
                    throw new RuntimeException();
                }
            }
        },"t2");


        t2.start();
//        t1.start();

        TimeUnit.SECONDS.sleep(3);
        System.out.println("ThreadSyncLockMain notify");
        obj.notify();
    }
}
